var http = require("http");
var url = require('url');
var qs = require('querystring');

function post(path, data, success, error) {
    var reqData = data || {};
    var postData = qs.stringify(reqData);
    var options = {
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
            'Content-Length': postData.length
        }
    };

    var p = url.parse(path);
    if (!p["protocol"] || !p["host"] || !p["pathname"]) {
        error && error('无效的访问地址');
        return;
    }
    options.host = p.hostname;
    options.port = p.port;
    options.path = p.pathname;
    options.method = 'post';

    var req = http.request(options, function(res) {
        var resData = '';
        res.on('data', function(chunk) {
            resData += chunk;
        });
        res.on('end', function() {
            success && success(resData);
        });
    });

    req.on('error', function(e) {
        error && error(e);
    });

    req.write(postData);

    req.end();
}

module.exports = {
    post: post
};
